<template>
  <el-main>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>工作流管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              创建工作流
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedKeys.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        ref="searchRef"
        :model="searchParam"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="工作流名称" prop="name">
          <el-input
            v-model="searchParam.param.name"
            placeholder="请输入工作流名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="searchParam.param.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in WORKFLOW_CATEGORY_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchParam.param.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="option in WORKFLOW_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="工作流名称" width="200" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" width="250" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleDesign(row)">
              设计
            </el-button>
            <el-button type="info" size="small" @click="handleInstances(row)">
              实例
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              type="warning" 
              size="small" 
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button 
              v-if="row.status === 1" 
              type="danger" 
              size="small" 
              @click="handleStop(row)"
            >
              停用
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParam.curPage"
          v-model:page-size="searchParam.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="searchParam.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 工作流表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="工作流名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入工作流名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入工作流描述" 
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="option in WORKFLOW_CATEGORY_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="formData.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="option in WORKFLOW_STATUS_OPTIONS"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 工作流设计器对话框 -->
    <el-dialog
      v-model="designDialogVisible"
      title="工作流设计"
      width="90%"
      :close-on-click-modal="false"
      class="workflow-design-dialog"
    >
      <WorkflowEditor 
        v-if="designDialogVisible"
        :workflow-id="currentWorkflowId"
        @save="handleDesignSave"
        @close="designDialogVisible = false"
      />
    </el-dialog>

    <!-- 工作流实例对话框 -->
    <el-dialog
      v-model="instanceDialogVisible"
      title="工作流实例"
      width="80%"
      :close-on-click-modal="false"
    >
      <WorkflowInstance 
        v-if="instanceDialogVisible"
        :workflow-id="currentWorkflowId"
        @close="instanceDialogVisible = false"
      />
    </el-dialog>
  </el-main>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue';
import { 
  getWorkflowList, 
  addWorkflow, 
  updateWorkflow, 
  deleteWorkflow, 
  deleteWorkflows,
  publishWorkflow,
  stopWorkflow
} from '@/api/workflow';
import type { Workflow, WorkflowQuery, WorkflowForm } from '@/api/workflow/WorkflowModel';
import { 
  WORKFLOW_STATUS_OPTIONS, 
  WORKFLOW_CATEGORY_OPTIONS 
} from '@/api/workflow/WorkflowModel';
import WorkflowEditor from './WorkflowEditor.vue';
import WorkflowInstance from './WorkflowInstance.vue';

// 响应式数据
const searchRef = ref<FormInstance>();
const formRef = ref<FormInstance>();

// 表格数据
const tableData = ref<Workflow[]>([]);
const loading = ref(false);

// 搜索参数
const searchParam = reactive<WorkflowQuery>({
  curPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  param: {
    name: '',
    category: '',
    status: undefined
  }
});

// 选中的行
const selectedKeys = ref<number[]>([]);

// 对话框
const dialogVisible = ref(false);
const designDialogVisible = ref(false);
const instanceDialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);

// 当前操作的工作流ID
const currentWorkflowId = ref<number | null>(null);

// 表单数据
const formData = reactive<WorkflowForm>({
  name: '',
  description: '',
  category: '',
  version: '1.0.0',
  status: 0,
  flowData: '{"nodes":[],"edges":[]}'
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入工作流描述', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ]
};

// 获取分类标签类型
const getCategoryTagType = (category: string) => {
  const typeMap = {
    'approval': 'primary',
    'business': 'success',
    'system': 'warning',
    'other': 'info'
  };
  return typeMap[category as keyof typeof typeMap] || 'info';
};

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const option = WORKFLOW_CATEGORY_OPTIONS.find(opt => opt.value === category);
  return option?.label || '未知';
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  };
  return typeMap[status as keyof typeof typeMap] || 'info';
};

// 获取状态标签
const getStatusLabel = (status: number) => {
  const option = WORKFLOW_STATUS_OPTIONS.find(opt => opt.value === status);
  return option?.label || '未知';
};

// 获取工作流列表
const loadWorkflowList = async () => {
  try {
    loading.value = true;
    const response = await getWorkflowList(searchParam);
    tableData.value = response.data.records || [];
    searchParam.total = response.data.total || 0;
    searchParam.pages = response.data.pages || 0;
  } catch (error) {
    ElMessage.error('获取工作流列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchParam.curPage = 1;
  loadWorkflowList();
};

// 重置
const handleReset = () => {
  searchRef.value?.resetFields();
  // 手动重置搜索参数
  searchParam.param.name = '';
  searchParam.param.category = '';
  searchParam.param.status = undefined;
  searchParam.curPage = 1;
  loadWorkflowList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  searchParam.pageSize = val;
  searchParam.curPage = 1;
  loadWorkflowList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  searchParam.curPage = val;
  loadWorkflowList();
};

// 选择改变
const handleSelectionChange = (selection: Workflow[]) => {
  selectedKeys.value = selection.map(item => item.id);
};

// 添加工作流
const handleAdd = () => {
  dialogTitle.value = '创建工作流';
  resetForm();
  dialogVisible.value = true;
};

// 编辑工作流
const handleEdit = (data: Workflow) => {
  dialogTitle.value = '编辑工作流';
  Object.assign(formData, data);
  dialogVisible.value = true;
};

// 设计工作流
const handleDesign = (data: Workflow) => {
  currentWorkflowId.value = data.id;
  designDialogVisible.value = true;
};

// 查看实例
const handleInstances = (data: Workflow) => {
  currentWorkflowId.value = data.id;
  instanceDialogVisible.value = true;
};

// 发布工作流
const handlePublish = async (data: Workflow) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布工作流"${data.name}"吗？`,
      '发布确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await publishWorkflow(data.id);
    ElMessage.success('发布成功');
    loadWorkflowList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败');
    }
  }
};

// 停用工作流
const handleStop = async (data: Workflow) => {
  try {
    await ElMessageBox.confirm(
      `确定要停用工作流"${data.name}"吗？`,
      '停用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await stopWorkflow(data.id);
    ElMessage.success('停用成功');
    loadWorkflowList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停用失败');
    }
  }
};

// 删除工作流
const handleDelete = async (data: Workflow) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工作流"${data.name}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteWorkflow(data.id);
    ElMessage.success('删除成功');
    loadWorkflowList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请选择要删除的工作流');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedKeys.value.length} 个工作流吗？删除后不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteWorkflows(selectedKeys.value);
    ElMessage.success('批量删除成功');
    selectedKeys.value = [];
    loadWorkflowList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败');
    }
  }
};

// 设计器保存
const handleDesignSave = () => {
  ElMessage.success('保存成功');
  loadWorkflowList();
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
    category: '',
    version: '1.0.0',
    status: 0,
    flowData: '{"nodes":[],"edges":[]}'
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (formData.id) {
      await updateWorkflow(formData);
      ElMessage.success('更新成功');
    } else {
      await addWorkflow(formData);
      ElMessage.success('添加成功');
    }
    
    dialogVisible.value = false;
    loadWorkflowList();
  } catch (error) {
    ElMessage.error(formData.id ? '更新失败' : '添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadWorkflowList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}

:deep(.workflow-design-dialog .el-dialog__body) {
  padding: 0;
  height: 80vh;
}
</style>

